package camelinaction;

import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.apache.camel.BeanInject;
import org.apache.camel.component.netty4.NettyConsumer;
import org.apache.camel.component.netty4.ServerInitializerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

@Component
public class SampleServerInitializerFactory extends ServerInitializerFactory implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Autowired
    private ServerHandler serverHandler;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext){
        this.applicationContext = applicationContext;
    }

    //@Override
    protected void initChannel(Channel ch) throws Exception {

        /*channelPipeline.addLast("encoder-SD", new StringEncoder(CharsetUtil.UTF_8));
        channelPipeline.addLast("decoder-DELIM", new DelimiterBasedFrameDecoder(maxLineSize, true, Delimiters.lineDelimiter()));
        channelPipeline.addLast("decoder-SD", new StringDecoder(CharsetUtil.UTF_8));
        // here we add the default Camel ServerChannelHandler for the consumer, to allow Camel to route the message etc.
        channelPipeline.addLast("handler", new ServerChannelHandler(consumer));*/

        //根据ch17章中的内容，定义了这几个参数。这个长度，仅仅是消息体的长度。
        ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024*1024,8,4));
        ch.pipeline().addLast(new FullRequestParse());

        ch.pipeline().addLast(new ResponseEncoder());
        ch.pipeline().addLast(serverHandler);
    }

    @Override
    public ServerInitializerFactory createPipelineFactory(NettyConsumer nettyConsumer) {

        return applicationContext.getBean(SampleServerInitializerFactory.class);
    }
}
